import socket,binascii

def readline(server):
    line = server.readline()
    print(line, end="")


def sendmail(from_addr, to_addr, subject, message):
    # 创建套接字
    s = socket.socket()

    # 获取服务器地址
    addr = socket.getaddrinfo("smtp.qq.com", 25)
    print(addr[0][-1])
    # 连接服务器
    s.connect(addr[0][-1])

    # 从服务器读一行
    server = s.makefile()
    readline(server)

    # 向服务器发送消息
    s.sendall("helo localhost\r\n".encode())
    readline(server)
    readline(server)
    readline(server)

    # 发送登录命令
    s.sendall("auth login\r\n".encode())
    readline(server)

    # 发送用户名
    s.sendall(binascii.b2a_base64("QQ号".encode(), newline=False))
    s.sendall("\r\n".encode())
    readline(server)

    # 发送授权码
    s.sendall(binascii.b2a_base64("授权码".encode(), newline=False))
    s.sendall("\r\n".encode())
    readline(server)

    # 发送发件人地址
    cmd = "mail from: <" + from_addr + ">\r\n"
    s.sendall(cmd.encode())
    readline(server)

    # 发送收件人地址
    cmd = "rcpt to: <" + to_addr + ">\r\n"
    s.sendall(cmd.encode())
    readline(server)

    # 发送data命令
    s.sendall("data\r\n".encode())
    readline(server)

    # 发送邮件头
    s.sendall("to: <geez@163.com>\r\n".encode())
    s.sendall("subject: =?utf-8?B?".encode())
    s.sendall(binascii.b2a_base64(subject.encode(), newline=False))
    s.sendall("?=\r\n".encode())
    s.sendall("MIME-Version: 1.0\r\n".encode())
    s.sendall("Content-Type: text/plain; charset=utf-8\r\n".encode())
    s.sendall("\r\n".encode())

    # 发送邮件正文
    s.sendall(message.encode())
    s.sendall("\r\n.\r\n".encode())
    readline(server)

    # 结束会话
    s.sendall("quit\r\n".encode())
    readline(server)

    # 断开连接
    s.close()
